package com.lsn.simulator.utils;

import com.lsn.simulator.utils.bean.CityList;
import com.thoughtworks.xstream.XStream;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.json.JSONObject;
import org.json.XML;

public class MyUtils {
    public static Object toBean(Class<?> clazz, String xml) {
        Object xmlObject = null;
        XStream xstream = new XStream();
        xstream.processAnnotations(clazz);
        xstream.autodetectAnnotations(true);
        xmlObject= xstream.fromXML(xml);

        return xmlObject;
    }

    public static void main(String[] args) {
        String str = "" +
                "<c c1=\"0\">\r\n" +
                "    <d d1=\"101280101\" d2=\"广州\" d3=\"guangzhou\" d4=\"广东\"/>\r\n" +
                "    <d d1=\"101280102\" d2=\"番禺\" d3=\"panyu\" d4=\"广东\"/>\r\n" +
                "    <d d1=\"101280103\" d2=\"从化\" d3=\"conghua\" d4=\"广东\"/>\r\n" +
                "</c>";
        CityList c = (CityList)toBean(CityList.class,str);
        System.out.println(c.getCityList().get(0));
    }

    public static String json2xml(String jsonString) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        xmlSerializer.setTypeHintsEnabled(false);
        String xml = xmlSerializer.write(JSONSerializer.toJSON(jsonString));
        xml = xml.replace("<o>", "").replace("</o>", "");
        xml = xml.replaceAll("\r\n", "").concat("\r\n");
        return xml;
    }
    /**
     * xml 转 json
     */
    public static String xml2json(String xmlString) {
        JSONObject jsonObject = XML.toJSONObject(xmlString);

        return jsonObject.toString(3);
    }

}
